package com.lishuang.pet.service.impl;

import com.lishuang.basic.exception.BusinessException;
import com.lishuang.basic.service.IBaiduAiAuditService;
import com.lishuang.basic.service.impl.BaseServiceImpl;
import com.lishuang.basic.util.CodeGenerateUtils;
import com.lishuang.basic.util.DistanceUtil;
import com.lishuang.basic.util.LoginContext;
import com.lishuang.basic.util.PageList;
import com.lishuang.order.domain.OrderPetAcquisition;
import com.lishuang.order.mapper.OrderPetAcquisitionMapper;
import com.lishuang.org.domain.Employee;
import com.lishuang.org.domain.Shop;
import com.lishuang.org.mapper.EmployeeMapper;
import com.lishuang.org.mapper.ShopMapper;
import com.lishuang.pet.domain.Pet;
import com.lishuang.pet.domain.PetDetail;
import com.lishuang.pet.domain.SearchMasterMsg;
import com.lishuang.pet.domain.SearchMasterMsgAuditLog;
import com.lishuang.pet.dto.MsgDto;
import com.lishuang.pet.mapper.PetDetailMapper;
import com.lishuang.pet.mapper.PetMapper;
import com.lishuang.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.lishuang.pet.mapper.SearchMasterMsgMapper;
import com.lishuang.pet.query.SearchMasterMsgQuery;
import com.lishuang.pet.service.ISearchMasterMsgService;
import com.lishuang.user.domain.Logininfo;
import com.lishuang.user.domain.User;
import com.lishuang.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private PetDetailMapper petDetailMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    /**
     * 发布寻主消息
     *
     * @param
     * @return
     */
    @Override
    public void publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLoginUser(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());

        //1.添加寻主消息
        searchMasterMsgMapper.save(searchMasterMsg);
        String text = "" + searchMasterMsg.getName() + searchMasterMsg.getTitle() + searchMasterMsg.getAddress();//文字
        //2.智能审核
        Boolean TextBoo = baiduAiAuditService.textAudit(text);//文字审核
        String resources = searchMasterMsg.getResources();//图片，视频
        Boolean ImgBoo = baiduAiAuditService.imageAudit(resources);//图片，视频审核
        if (TextBoo && ImgBoo) {
            //2.1.审核通过： 修改寻主消息状态1【审核通过待处理】 + 将当前寻主消息分配给最近的门店 + 发短信告诉它 + 添加审核日志
            //将当前寻主消息分配给最近的门店
            //1)查询所有店铺
            List<Shop> shops = shopMapper.loadAll();
            //2)从中获取满足条件店铺 小于50公里
            Shop shop = DistanceUtil
                    .getNearestShop(DistanceUtil.getPoint(searchMasterMsg.getAddress()), shops);
            //3）如果找到了，把消息分给店铺并发消息
            if (shop != null) {
                searchMasterMsg.setShopId(shop.getId());

                //发短信告诉它
                //调用SmsUtils发送短信
                //SmsUtil.sendSms(phone,"分配了寻主消息给你，请接收。。。");
                System.out.println("分配了寻主消息给你，请接收。。。" + searchMasterMsg.getTitle());
            }
            //4)如果没有找到放入寻主池-不做任何处理

            //审核通过： 修改寻主消息状态1【审核通过待处理】
            searchMasterMsg.setState(1);
            searchMasterMsg.setNote("审核通过");
            searchMasterMsg.setUserId(user.getId());
            searchMasterMsgMapper.update(searchMasterMsg);
            //审核通过： 添加审核日志
            SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
            searchMasterMsgAuditLog.setState(1);
            searchMasterMsgAuditLog.setNote("审核通过");
            searchMasterMsgAuditLog.setAuditId(user.getId());
            searchMasterMsgAuditLog.setMsgId(searchMasterMsg.getId());
            searchMasterMsgAuditLogMapper.save(searchMasterMsgAuditLog);

        } else {

            //审核失败：修改寻主消息状态0
            searchMasterMsg.setState(0);
            searchMasterMsg.setNote("审核失败，数据违规。。。");
            searchMasterMsg.setUserId(user.getId());
            searchMasterMsgMapper.update(searchMasterMsg);
            //审核失败：添加审核日志
            SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
            searchMasterMsgAuditLog.setState(0);
            searchMasterMsgAuditLog.setNote("审核失败，数据违规。。。");
            searchMasterMsgAuditLog.setAuditId(user.getId());
            searchMasterMsgAuditLog.setMsgId(searchMasterMsg.getId());
            searchMasterMsgAuditLogMapper.save(searchMasterMsgAuditLog);
            searchMasterMsgMapper.remove(searchMasterMsg.getId());
            throw new BusinessException("数据违规。。。");
        }

    }

    /**
     * 用户查询寻主消息
     *
     * @param
     */
    @Override
    public PageList<SearchMasterMsg> userSearchMasterMsg(SearchMasterMsgQuery query, HttpServletRequest request) {
        {
            Logininfo logininfo = LoginContext.getLoginUser(request);
            User user = userMapper.loadByLogininfoId(logininfo.getId());
            query.setUserId(user.getId());
            return super.queryPage(query);
        }
    }

    /**
     * 处理中的寻主消息
     *
     * @param
     */
    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLoginUser(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        if (employee.getShop_id() != null) {
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    /**
     * 拒单
     *
     * @param id
     */
    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    /**
     * 接单
     *
     * @param msgDto
     */
    @Override
    public void accept(MsgDto msgDto) {

        Long empId = msgDto.getHandler();
        Long msgId = msgDto.getMsgId();
        String note = msgDto.getNote();

        //1.校验改寻主消息是否已经在处理，报错
        OrderPetAcquisition orderTmp = orderPetAcquisitionMapper.loadByMsgId(msgId);
        if (orderTmp != null) {
            throw new BusinessException("已经被接单，正在处理中！");
        }

        //获取员工信息
        Employee employee = employeeMapper.loadById(empId);

        //创建宠物信息
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(msgId);
        Pet pet = searchMasterMsg2pet(searchMasterMsg);
        petMapper.save(pet);

        //创建宠物详情信息
        PetDetail petDetail = new PetDetail();
        petDetail.setPetId(pet.getId());
        petDetailMapper.save(petDetail);

        //创建宠物收购订单
        OrderPetAcquisition order = buildOrder(searchMasterMsg, empId, pet);
        orderPetAcquisitionMapper.save(order);

        //3 发送消息给对应的工作人员
        System.out.println(employee.getEmail() + "-->邮件通知：您有新的" + order.getOrderSn() + "订单要处理！");
        System.out.println(employee.getPhone() + "-->短信通知：您有新的" + order.getOrderSn() + "订单要处理！");

    }

    private OrderPetAcquisition buildOrder(SearchMasterMsg searchMasterMsg, Long empId, Pet pet) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(pet.getUserId());
        order.setOrderSn(orderSn);
        order.setDigest(searchMasterMsg.getName() + "的收购订单");
        long time = System.currentTimeMillis() + 2 * 24 * 60 * 60 * 1000;
        order.setLastcomfirmtime(new Date(time));
        order.setState(0);//待处理
        order.setPrice(new BigDecimal(searchMasterMsg.getPrice()));
        order.setPetId(pet.getId());
        order.setUserId(pet.getUserId());
        order.setShopId(pet.getShopId());
        order.setAddress(searchMasterMsg.getAddress());
        order.setEmpId(empId);
        order.setSearchMasterMsgId(searchMasterMsg.getId());
        return order;
    }

    private Pet searchMasterMsg2pet(SearchMasterMsg searchMasterMsg) {
        Pet pet = new Pet();
        pet.setName(searchMasterMsg.getName());
        pet.setResources(searchMasterMsg.getResources());
        pet.setTypeId(searchMasterMsg.getPetType());
        //就要获取处理人的店铺id
        pet.setShopId(searchMasterMsg.getShopId());
        pet.setUserId(searchMasterMsg.getUserId());
        pet.setSearchMasterMsgId(searchMasterMsg.getId());
        //用户发布时需要的价格 收购回来就是成本价
        pet.setCostprice(searchMasterMsg.getPrice());
        return pet;
    }
}
